<template>
  <ContentWrap>
    <!-- 搜索工作栏：保持不变 -->
    <search
      :schema="searchSchema"
      label-width="85px"
      :expand="false"
      expandField="inboundTime"
      @search="getList"
      @reset="getList"
      size="small"
    >
      <template #actionMore>
        <el-button
          type="primary"
          plain
          size="small"
          @click="handleImportLog"
          v-hasPermi="['distm:schedule-record:create']"
        >
          新建
        </el-button>
        <el-button
          type="primary"
          plain
          size="small"
          @click="handleImportLog"
          v-hasPermi="['distm:schedule-record:create']"
        >
          配餐
        </el-button>
        <el-button
          type="primary"
          plain
          size="small"
          @click="handleImportLog"
          v-hasPermi="['distm:schedule-record:create']"
        >
          高端用户
        </el-button>
        <el-button
          type="primary"
          plain
          size="small"
          @click="handleImportLog"
          v-hasPermi="['distm:schedule-record:create']"
        >
          备注
        </el-button>

        <el-button
          type="primary"
          plain
          size="small"
          @click="handleFlightTimeClick"
          v-hasPermi="['distm:schedule-record:create']"
        >
          航班时间
        </el-button>
        <el-button
          type="primary"
          plain
          size="small"
          @click="handleFlightNewsClick"
          v-hasPermi="['distm:schedule-record:create']"
        >
          航班动态
        </el-button>
        <el-button
          type="primary"
          plain
          size="small"
          @click="handleFlightZongHeClick"
          v-hasPermi="['distm:schedule-record:create']"
        >
          综合信息
        </el-button>
        <el-button
          type="primary"
          plain
          size="small"
          @click="handleImportLog"
          v-hasPermi="['distm:schedule-record:create']"
        >
          单据状态
        </el-button>
        <el-button
          type="primary"
          plain
          size="small"
          @click="handleImportLog"
          v-hasPermi="['distm:schedule-record:create']"
        >
          打印报表
        </el-button>
        <el-button
          type="primary"
          plain
          size="small"
          @click="handleImportLog"
          v-hasPermi="['distm:schedule-record:create']"
        >
          单据管理
        </el-button>
        <el-button
          type="primary"
          plain
          size="small"
          @click="handleFlightBiaoZhiClick"
          v-hasPermi="['distm:schedule-record:create']"
        >
          标志
        </el-button>
        <el-button
          type="primary"
          plain
          size="small"
          @click="handleImportLog"
          v-hasPermi="['distm:schedule-record:create']"
        >
          获取最新
        </el-button>
        <el-button
          type="primary"
          plain
          size="small"
          @click="handleSyncQuarter"
          v-hasPermi="['distm:schedule-record:create']"
        >
          同步季度计划
        </el-button>
        <el-button
          type="success"
          plain
          size="small"
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['distm:schedule-record:export']"
        >
          <Icon icon="ep:download" /> 导出
        </el-button>
      </template>
    </search>
  </ContentWrap>
  <!-- 列表：操作列表头仅显示“操作”文本 -->
  <ContentWrap>
    <el-splitter direction="vertical" :gutter="0">
      <el-splitter-panel :min="100" collapsible>
        <TableV2
          :columns="leftColumns"
          :data="leftList"
          :loading="loading"
          height="65vh"
          :table-set-props="{
            fixed: true,
            rowKey: 'id',
            rowClass: tableRowClassName,
            rowHeight: 50,
            rowEventHandlers: {
              onClick: handleRowClick,
              onDblclick: handleDbRowClick
            }
          }"
        />
      </el-splitter-panel>
      <el-splitter-panel :min="100" collapsible>
        <TableV2
          :columns="centerColumns"
          :data="centerList"
          :loading="loading"
          height="65vh"
          :table-set-props="{
            fixed: true,
            rowKey: 'id',
            rowClass: tableRowClassName,
            rowHeight: 50,
            rowEventHandlers: {
              onClick: handleRowClick,
              onDblclick: handleDbRowClick
            }
          }"
        />
      </el-splitter-panel>
      <el-splitter-panel :min="100" collapsible>
        <TableV2
          :columns="rightColumns"
          :data="rightList"
          :loading="loading"
          height="65vh"
          :table-set-props="{
            fixed: true,
            rowClass: tableRowClassName,
            rowHeight: 50,
            rowKey: 'id',
            rowEventHandlers: {
              onClick: handleRowClick,
              onDblclick: handleDbRowClick
            }
          }"
        />
      </el-splitter-panel>
    </el-splitter>
  </ContentWrap>

  <!-- 数量编辑弹窗 -->
  <el-dialog
    title="编辑数量信息"
    v-model="quantityDialogVisible"
    width="800px"
    :close-on-click-modal="false"
  >
    <el-form ref="quantityFormRef" :model="currentRow" label-width="120px">
      <el-form-item label="销售数量：">
        <el-row :gutter="10">
          <el-col :span="6">
            <el-input
              v-model="currentRow.crewSaleQty"
              placeholder="J"
              @input="handleNumberInput(currentRow, 'crewSaleQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="currentRow.bussClassSaleQty"
              placeholder="S"
              @input="handleNumberInput(currentRow, 'bussClassSaleQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="currentRow.premEcoClassSaleQty"
              placeholder="G"
              @input="handleNumberInput(currentRow, 'premEcoClassSaleQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="currentRow.ecoClassSaleQty"
              placeholder="Y"
              @input="handleNumberInput(currentRow, 'ecoClassSaleQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="配餐数量：">
        <el-row :gutter="10">
          <el-col :span="6">
            <el-input
              v-model="currentRow.crewQty"
              placeholder="J"
              @input="handleNumberInput(currentRow, 'crewQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="currentRow.bussClassQty"
              placeholder="S"
              @input="handleNumberInput(currentRow, 'bussClassQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="currentRow.premEcoClassQty"
              placeholder="G"
              @input="handleNumberInput(currentRow, 'premEcoClassQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="currentRow.ecoClassQty"
              placeholder="Y"
              @input="handleNumberInput(currentRow, 'ecoClassQty', $event)"
              type="number"
              min="0"
            />
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="quantityDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleQuantitySave">确定</el-button>
    </template>
  </el-dialog>

  <!-- 其他弹窗组件（完全保留） -->
  <FlightLogImportForm ref="importFormRef" @success="getList" />
  <ProduceRecordForm ref="formRef" @success="getList" />
  <ScheduleRecordAddForm ref="formAddRef" @success="getList" />

  <FlightTime
    ref="flightTimeRef"
    :api="ScheduleRecordApi.updateScheduleRecord"
    @success="getList"
  />
  <el-dialog width="80vw" title="航班动态" v-model="flightTimeDialogVisible" top="100px">
    <FlightNews />
  </el-dialog>
  <el-dialog width="80vw" title="航班信息" v-model="flightInfoVisible">
    <FlightInfo />
  </el-dialog>
  <el-dialog width="90vw" title="综合信息" v-model="flightZongHeVisble">
    <FlightZongHe />
  </el-dialog>
  <el-dialog width="600px" title="标志" v-model="flightBiaozhiVisible">
    <BiaoZhi />
  </el-dialog>
</template>

<script lang="tsx" setup>
import { ref, reactive, onMounted, computed, nextTick, watch, h } from 'vue'
import type { Column } from 'element-plus'
import {
  ElTag,
  ElInput,
  ElButton,
  ElDropdown,
  ElDropdownMenu,
  ElDropdownItem,
  ElIcon,
  ElTooltip,
  ElDialog,
  ElForm,
  ElFormItem,
  ElRow,
  ElCol
} from 'element-plus'
import { DArrowRight, Operation, Timer } from '@element-plus/icons-vue'

// 保留原始所有导入
import { formatDate } from '@/utils/formatTime'
import download from '@/utils/download'
import { ScheduleRecordApi, ScheduleRecordVO } from '@/api/distm/schedule'
import FlightLogImportForm from './FlightLogImportForm.vue'
import ProduceRecordForm from '@/views/pplan/producerecord/ProduceRecordForm.vue'
import ScheduleRecordAddForm from '@/views/distm/schedule/ScheduleRecordAddForm.vue'
import DictTag from '@/components/DictTag/src/DictTag.vue'
import { DICT_TYPE } from '@/utils/dict'

import { FormSchema } from '@/types/form'
import { formatProcessStatus, formatTimeString } from '@/utils/formatter'
import { ProcessStatus } from '@/utils/constants'
import FlightTime from './components/FlightTime.vue'
import FlightNews from '../flightnews/index.vue'
import FlightInfo from './components/FlightInfo.vue'
import FlightZongHe from './components/FightZongHe.vue'
import BiaoZhi from './components/BiaoZhi.vue'

/** 基础配置（保留原始逻辑） */
defineOptions({ name: 'ScheduleRecord' })

const flightTimeRef = ref<any>(null)

const searchSchema = ref<FormSchema[]>([
  {
    field: 'recordDate',
    label: '日期',
    component: 'DatePicker',
    colProps: {
      span: 6
    },
    componentProps: {
      placeholder: '选择记录日期',
      valueFormat: 'YYYY-MM-DD',
      clearable: true,
      type: 'date',
      class: '!w-160px'
    }
  },
  {
    field: 'flightNo',
    label: '航班号',
    component: 'Input',
    colProps: {
      span: 6
    },
    componentProps: {
      placeholder: '请输入航班号',
      clearable: true
    }
  },
  {
    field: 'airlineComp',
    label: '航空公司',
    component: 'Input',
    colProps: {
      span: 6
    },
    componentProps: {
      placeholder: '请输入航空公司',
      clearable: true
    }
  },
  {
    field: 'inboundFlight',
    label: '进港航班',
    colProps: {
      span: 6
    },
    component: 'Input',
    componentProps: {
      placeholder: '请输入进港航班',
      clearable: true
    }
  },
  {
    field: 'machineNo',
    label: '机号',
    component: 'Input',
    colProps: {
      span: 6
    },
    componentProps: {
      placeholder: '请输入机号',
      clearable: true
    }
  },
  {
    field: 'remarks',
    label: '调度备注包含',
    component: 'Input',
    colProps: {
      span: 6
    },
    componentProps: {
      placeholder: '请输入调度备注',
      clearable: true
    }
  },
  {
    field: 'noRemarks',
    label: '调度备注不包',
    component: 'Input',
    colProps: {
      span: 6
    },
    componentProps: {
      placeholder: '请输入调度备注',
      clearable: true
    }
  }
])

const buildQuantifyColumn = (row) => {
  return (
    <div
      style="display: flex; flex-direction: column; gap: 2px; width: 100%; cursor: pointer;"
      onClick={() => openQuantityEdit(row)}
    >
      {/* 第一行：标题行 */}
      <div style="display: flex; font-weight: 500; font-size: 12px;">
        <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
          <ElTooltip content="J" placement="top">
            <span>J</span>
          </ElTooltip>
        </div>
        /
        <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
          <ElTooltip content="S" placement="top">
            <span>S</span>
          </ElTooltip>
        </div>
        /
        <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
          <ElTooltip content="G" placement="top">
            <span>G</span>
          </ElTooltip>
        </div>
        /
        <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
          <ElTooltip content="Y" placement="top">
            <span>Y</span>
          </ElTooltip>
        </div>
      </div>

      {/* 第二行：销售数量行 */}
      <div style="display: flex; font-size: 12px;">
        <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
          <ElTooltip content={row.crewSaleQty || '-'} placement="top">
            <span>{row.crewSaleQty || '-'}</span>
          </ElTooltip>
        </div>
        /
        <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
          <ElTooltip content={row.bussClassSaleQty || '-'} placement="top">
            <span>{row.bussClassSaleQty || '-'}</span>
          </ElTooltip>
        </div>
        /
        <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
          <ElTooltip content={row.premEcoClassSaleQty || '-'} placement="top">
            <span>{row.premEcoClassSaleQty || '-'}</span>
          </ElTooltip>
        </div>
        /
        <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
          <ElTooltip content={row.ecoClassSaleQty || '-'} placement="top">
            <span>{row.ecoClassSaleQty || '-'}</span>
          </ElTooltip>
        </div>
      </div>
      {/* 第三行：数量行 */}
      <div style="display: flex; font-size: 12px;">
        <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
          <ElTooltip content={row.crewQty || '-'} placement="top">
            <span>{row.crewQty || '-'}</span>
          </ElTooltip>
        </div>
        /
        <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
          <ElTooltip content={row.bussClassQty || '-'} placement="top">
            <span>{row.bussClassQty || '-'}</span>
          </ElTooltip>
        </div>
        /
        <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
          <ElTooltip content={row.premEcoClassQty || '-'} placement="top">
            <span>{row.premEcoClassQty || '-'}</span>
          </ElTooltip>
        </div>
        /
        <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
          <ElTooltip content={row.ecoClassQty || '-'} placement="top">
            <span>{row.ecoClassQty || '-'}</span>
          </ElTooltip>
        </div>
      </div>
    </div>
  )
}

const baseColumns: Column[] = [
  {
    key: 'recordDate',
    dataKey: 'recordDate',
    title: '日',
    width: 44,
    cellRenderer: ({ cellData }) => {
      return (
        <ElTooltip content={cellData ? formatDate(cellData, 'YYYY-MM-DD') : ''} placement="top">
          <span>{cellData ? formatDate(cellData, 'DD') : ''}</span>
        </ElTooltip>
      )
    }
  },
  {
    key: 'inboundFlight',
    dataKey: 'inboundFlight',
    title: '进港航班',
    width: 150,
    editable: true,
    editWidth: 120
  },
  { key: 'flightNo', dataKey: 'flightNo', title: '航班号', width: 120 },
  {
    key: 'machineNo',
    dataKey: 'machineNo',
    title: '机号',
    width: 140,
    editable: true,
    editWidth: 110
  },
  { key: 'route', dataKey: 'route', title: '航线', width: 180 }, // 新增航线列
  {
    key: 'depTime',
    dataKey: 'depTime',
    title: '起飞时间',
    width: 100,
    editable: true,
    editWidth: 100,
    cellRenderer: ({ cellData }) => {
      return <span>{formatTimeString(cellData)}</span>
    }
  },
  {
    key: 'preLandingTime',
    dataKey: 'preLandingTime',
    title: '预落时间',
    width: 100,
    editable: true,
    editWidth: 100,
    cellRenderer: ({ cellData }) => {
      return <span>{formatTimeString(cellData)}</span>
    }
  },
  {
    key: 'shiLuoTime',
    dataKey: 'shiLuoTime',
    title: '实落时间',
    width: 100,
    editable: true,
    cellRenderer: ({ cellData }) => {
      return <span>{formatTimeString(cellData)}</span>
    }
  },
  {
    key: 'inboundTime',
    dataKey: 'inboundTime',
    title: '进港时间',
    width: 100,
    editable: true,
    editWidth: 100,
    cellRenderer: ({ cellData }) => {
      return <span>{formatTimeString(cellData)}</span>
    }
  },
  {
    key: 'airportStands',
    dataKey: 'airportStands',
    title: '机位',
    width: 130,
    editable: true,
    editWidth: 100
  },
  {
    key: 'remarks',
    dataKey: 'remarks',
    title: '备注',
    width: 200,
    editable: true,
    editWidth: 200
  },
  // 整合数量相关列
  {
    key: 'quantity',
    dataKey: 'quantity',
    title: '数量',
    width: 300,
    cellRenderer: ({ rowData }) => {
      return buildQuantifyColumn(rowData)
    }
  },
  {
    key: 'specialRemarks',
    dataKey: 'specialRemarks',
    title: '特殊说明',
    width: 200,
    editable: true,
    editWidth: 200
  },
  { key: 'aircraftType', dataKey: 'aircraftType', title: '机型', width: 120 },
  {
    key: 'airlineComp',
    dataKey: 'airlineComp',
    title: '所属公司',
    width: 120,
    cellRenderer: ({ cellData }) => {
      return <DictTag type={DICT_TYPE.PPLAN_AIRLINE_ID} value={cellData}></DictTag>
    }
  },
  {
    key: 'airlinePattern',
    dataKey: 'airlinePattern',
    title: '航班类型',
    width: 120,
    cellRenderer: ({ cellData }) => {
      return <DictTag type={DICT_TYPE.PPLAN_AIRLINE_TYPE} value={cellData}></DictTag>
    }
  },
  { key: 'company', dataKey: 'company', title: '所属公司', width: 120 },
  {
    key: 'pstatus',
    dataKey: 'pstatus',
    title: '生产状态',
    width: 120,
    cellRenderer: ({ cellData }) => {
      console.log('cellData', cellData)
      return <ElTag>{formatProcessStatus(cellData)}</ElTag>
    }
  }
]

const message = useMessage()
const { t } = useI18n()

const loading = ref(true)
const leftList = ref<ScheduleRecordVO[]>([])
const centerList = ref<ScheduleRecordVO[]>([])
const rightList = ref<ScheduleRecordVO[]>([])
const selectedRow = ref<ScheduleRecordVO | null>(null)
const flightTimeDialogVisible = ref(false)
const flightInfoVisible = ref(false)
const flightZongHeVisble = ref(false)
const flightBiaozhiVisible = ref(false)

const exportLoading = ref(false)
// 数量编辑弹窗相关
const quantityDialogVisible = ref(false)
const currentRow = ref<Partial<ScheduleRecordVO>>({})
const quantityFormRef = ref()

const leftColumns = computed(() => {
  const leftExCols = {
    pstatus: true,
    quantity: true,
    createTime: true,
    specialRemarks: true,
    remarks: true
  }
  const columns = baseColumns
    .filter((col) => !leftExCols[col.key as string])
    .map((elem) => ({ ...elem }))
  columns.push({
    key: 'actions',
    dataKey: 'actions',
    width: 50,
    fixed: 'right',
    cellRenderer: ({ rowData }) => (
      <el-button type="primary" link size="small">
        预落
      </el-button>
    )
  })
  return columns
})

const centerColumns = computed(() => {
  const centerExCols = {
    pstatus: true,
    quantity: true,
    createTime: true,
    specialRemarks: true,
    remarks: true
  }
  const columns = baseColumns
    .filter((col) => !centerExCols[col.key as string])
    .map((elem) => ({ ...elem }))
  columns.push({
    key: 'actions',
    dataKey: 'actions',
    width: 50,
    fixed: 'right',
    cellRenderer: ({ rowData }) => (
      <el-popover
        placement="bottom"
        trigger="hover"
        width={60}
        popper-class="!min-w-1px"
        v-slots={{
          reference: () => (
            <el-button type="primary" link size="small" icon={Operation}></el-button>
          ),
          default: () => {
            return (
              <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                <el-button type="primary" link size="small">
                  报航机
                </el-button>
                <el-button type="primary" link size="small">
                  实落
                </el-button>
              </div>
            )
          }
        }}
      ></el-popover>
    )
  })
  return columns
})

const rightColumns = computed(() => {
  const rightExCols = {
    pstatus: true,
    quantity: true,
    createTime: true,
    specialRemarks: true,
    remarks: true
  }
  const columns = baseColumns
    .filter((col) => !rightExCols[col.key as string])
    .map((elem) => ({ ...elem }))
  columns.push({
    key: 'actions',
    dataKey: 'actions',
    width: 50,
    fixed: 'right',
    cellRenderer: ({ rowData }) => (
      <el-popover
        placement="bottom"
        trigger="hover"
        width={60}
        popper-class="!min-w-1px"
        v-slots={{
          reference: () => (
            <el-button type="primary" link size="small" icon={Operation}></el-button>
          ),
          default: () => {
            return (
              <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                <el-button type="primary" link size="small">
                  装机
                </el-button>
                <el-button type="primary" link size="small">
                  完成
                </el-button>
                <el-button type="primary" link size="small">
                  上客
                </el-button>
                <el-button type="primary" link size="small">
                  起飞
                </el-button>
                <el-button type="primary" link size="small">
                  取消装机
                </el-button>
                <el-button type="primary" link size="small">
                  取消完成
                </el-button>
              </div>
            )
          }
        }}
      ></el-popover>
    )
  })
  return columns
})

const handleRowClick = ({ rowData }: { rowData: ScheduleRecordVO }) => {
  if (selectedRow.value && selectedRow.value.id === rowData.id) {
    selectedRow.value = null
    return
  }
  selectedRow.value = rowData
}

const handleDbRowClick = ({ rowData }) => {
  selectedRow.value = rowData
  flightTimeRef.value.open(rowData)
}

const handleFlightTimeClick = () => {
  if (selectedRow.value) {
    flightTimeRef.value.open(selectedRow.value)
  } else {
    message.warning('请先选择一行数据')
  }
}

const handleFlightNewsClick = () => {
  flightTimeDialogVisible.value = true
}

const handleFlightInfoClick = () => {
  if (selectedRow.value) {
    flightInfoVisible.value = true
  } else {
    message.warning('请先选择一行数据')
  }
}

const handleFlightZongHeClick = () => {
  if (selectedRow.value) {
    flightZongHeVisble.value = true
  } else {
    message.warning('请先选择一行数据')
  }
}

const handleFlightBiaoZhiClick = () => {
  if (selectedRow.value) {
    flightBiaozhiVisible.value = true
  } else {
    message.warning('请先选择一行数据')
  }
}

const formatDisplayTime = (timeString: string | undefined): string | null => {
  if (!timeString) return null
  return formatTimeString(timeString)
}

const isTimeColumn = (prop: string): boolean => {
  return ['inboundTime', 'preLandingTime', 'depTime'].includes(prop)
}

const isNumberColumn = (prop: string): boolean => {
  return [
    'crewQty',
    'bussClassQty',
    'premEcoClassQty',
    'ecoClassQty',
    'crewSaleQty',
    'bussClassSaleQty',
    'premEcoClassSaleQty',
    'ecoClassSaleQty'
  ].includes(prop)
}

const getColumnNameByProp = (prop: string): string => {
  const column = allColumns.find((col) => col.prop === prop)
  return column?.label || prop
}

/** 业务逻辑函数（保留原始） */
const getList = async (params?: any) => {
  loading.value = true
  try {
    const data = await ScheduleRecordApi.getScheduleRecordPage({
      ...(params || {}),
      pageIndex: 0,
      pageSize: 1000
    })
    // data.list.forEach((item) => {
    //   item._original = JSON.parse(JSON.stringify(item))
    //   item.inboundTime = formatTimeString(item.inboundTime)
    //   item.preLandingTime = formatTimeString(item.preLandingTime)
    //   item.depTime = formatTimeString(item.depTime)
    //   item.formattedOriginal = {
    //     inboundTime: item.inboundTime || '',
    //     preLandingTime: item.preLandingTime || '',
    //     depTime: item.depTime || '',
    //     machineNo: item.machineNo || '',
    //     airportStands: item.airportStands || '',
    //     inboundFlight: item.inboundFlight || '',
    //     depTimeStr: item.depTimeStr || '',
    //     inboundTimeStr: item.inboundTimeStr || '',
    //     remarks: item.remarks || '',
    //     bussClassQty: item.bussClassQty || '',
    //     crewSaleQty: item.crewSaleQty || '',
    //     bussClassSaleQty: item.bussClassSaleQty || '',
    //     premEcoClassSaleQty: item.premEcoClassSaleQty || '',
    //     ecoClassSaleQty: item.ecoClassSaleQty || '',
    //     crewQty: item.crewQty || '',
    //     premEcoClassQty: item.premEcoClassQty || '',
    //     ecoClassQty: item.ecoClassQty || '',
    //     specialRemarks: item.specialRemarks || ''
    //   }
    // })
    const list = data.list.filter((elem) => !elem.inboundTime)
    list.sort((a, b) => {
      return a.preLandingTime > b.preLandingTime ? 1 : -1
    })
    leftList.value = list
    const list2 = data.list.filter((elem) => !elem.preLandingTime && elem.inboundTime)
    list2.sort((a, b) => {
      return a.inboundTime > b.inboundTime ? 1 : -1
    })
    centerList.value = list2
    const list3 = data.list.filter((elem) => elem.shiLuoTime)
    list3.sort((a, b) => {
      return a.depTime > b.depTime ? 1 : -1
    })
    rightList.value = list3
  } catch (error: any) {
    message.error('获取列表失败，请稍后重试' + error.toString())
  } finally {
    loading.value = false
  }
}

const formRef = ref()
const openForm = (type: string, flightNo?: string) => {
  if (formRef.value && flightNo) formRef.value.openFlightNo(type, flightNo)
}

const formAddRef = ref()
const openAddForm = (flightNo?: string, recordDate?: string) => {
  if (formAddRef.value && flightNo) formAddRef.value.openAdd('create', flightNo, recordDate)
}

const handleColumnTimeInput = (row: any, prop: string, value: string) => {
  row[prop] = value.replace(/[^0-9]/g, '')
}

const handleColumnTimeBlur = async (row: any, prop: string) => {
  const current = row[prop]?.trim() || ''
  const original = row.formattedOriginal[prop] || ''
  if (current === original) return

  if (current && /^\d{2}:\d{2}$/.test(current)) {
    await handleFieldChange(row)
    return
  }

  if (current && (current.length !== 4 || !/^\d{4}$/.test(current))) {
    message.error(`请输入4位数字的${getColumnNameByProp(prop)}格式(HHmm)`)
    row[prop] = original
    return
  }

  if (current) {
    const formatted = formatTimeString(current)
    if (formatted) {
      if (formatted === original) {
        row[prop] = formatted
        return
      }
      row[prop] = formatted
      await handleFieldChange(row)
    } else {
      message.error('请输入有效的时间格式(HHmm)')
      row[prop] = original
    }
  } else {
    if (original !== '') await handleFieldChange(row)
  }
}

const handleNumberInput = (row: any, prop: string, value: string) => {
  // 先过滤非数字字符，再截取前9位以限制最大长度
  const numericValue = value.replace(/[^0-9]/g, '')
  row[prop] = numericValue.slice(0, 9)
}

const handleNumberBlur = async (row: any, prop: string) => {
  const current = row[prop]?.trim() || ''
  const original = row.formattedOriginal[prop] || ''
  if (current === original) return

  if (current && (isNaN(parseInt(current)) || parseInt(current) < 0)) {
    message.error(`请输入有效的${getColumnNameByProp(prop)}`)
    row[prop] = original
    return
  }

  await handleFieldChange(row)
}

const handleTextBlur = async (row: any, prop: string) => {
  const current = row[prop]?.trim() || ''
  const original = row.formattedOriginal[prop] || ''
  if (current === original) return
  await handleFieldChange(row)
}

const handleFieldChange = async (row: ScheduleRecordVO) => {
  try {
    if (!row || !row.id) {
      message.error('数据无效')
      return
    }

    const hasChange = Object.keys(row).some((key) => {
      if (key === '_original' || key === 'formattedOriginal') return false
      const original = row.formattedOriginal[key] || ''
      const current = row[key] || ''
      if (isTimeColumn(key)) return original !== current
      if (isNumberColumn(key)) return String(original) !== String(current)
      return original !== current
    })

    if (!hasChange) return

    const updateData = {
      ...row,
      bussClassQty: row.bussClassQty ? Number(row.bussClassQty) : undefined,
      crewSaleQty: row.crewSaleQty ? Number(row.crewSaleQty) : undefined,
      bussClassSaleQty: row.bussClassSaleQty ? Number(row.bussClassSaleQty) : undefined,
      premEcoClassSaleQty: row.premEcoClassSaleQty ? Number(row.premEcoClassSaleQty) : undefined,
      ecoClassSaleQty: row.ecoClassSaleQty ? Number(row.ecoClassSaleQty) : undefined,
      crewQty: row.crewQty ? Number(row.crewQty) : undefined,
      premEcoClassQty: row.premEcoClassQty ? Number(row.premEcoClassQty) : undefined,
      ecoClassQty: row.ecoClassQty ? Number(row.ecoClassQty) : undefined
    } as ScheduleRecordVO
    const res = await ScheduleRecordApi.updateScheduleRecord(updateData)
    message.success(res !== 'success' ? res : '更新成功')

    row._original = JSON.parse(JSON.stringify(row))
    row.formattedOriginal = {
      inboundTime: row.inboundTime || '',
      preLandingTime: row.preLandingTime || '',
      depTime: row.depTime || '',
      machineNo: row.machineNo || '',
      airportStands: row.airportStands || '',
      inboundFlight: row.inboundFlight || '',
      depTimeStr: item.depTimeStr || '',
      inboundTimeStr: item.inboundTimeStr || '',
      remarks: row.remarks || '',
      bussClassQty: row.bussClassQty || '',
      crewSaleQty: row.crewSaleQty || '',
      bussClassSaleQty: row.bussClassSaleQty || '',
      premEcoClassSaleQty: row.premEcoClassSaleQty || '',
      ecoClassSaleQty: row.ecoClassSaleQty || '',
      crewQty: row.crewQty || '',
      premEcoClassQty: row.premEcoClassQty || '',
      ecoClassQty: row.ecoClassQty || '',
      specialRemarks: row.specialRemarks || ''
    }
  } catch (err) {
    console.error('更新失败:', err)
    message.error('更新失败，请重试')
    await getList()
  }
}

// 数量编辑弹窗确认保存
const handleQuantitySave = async () => {
  try {
    if (!currentRow.value.id) {
      message.error('数据无效')
      return
    }
    // 深拷贝当前行数据用于比较
    const tempRow = JSON.parse(JSON.stringify(currentRow.value)) as ScheduleRecordVO
    // 调用通用更新方法
    await handleFieldChange(tempRow)
    // 关闭弹窗
    quantityDialogVisible.value = false
    // 刷新列表
    await getList()
  } catch (err) {
    console.error('数量更新失败:', err)
    message.error(t('common.updateFail'))
  }
}

const handleStatusChange = async (row: ScheduleRecordVO, newStatus: number) => {
  try {
    if (row.pstatus === newStatus) return
    await ScheduleRecordApi.updateScheduleRecord({ id: row.id, pstatus: newStatus })
    row.pstatus = newStatus
    message.success(t('common.updateSuccess'))
  } catch (err) {
    message.error(t('common.updateFail'))
    console.error('状态更新失败:', err)
  }
}

const importFormRef = ref()
const handleImportLog = () => importFormRef.value?.open()

const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const data = await ScheduleRecordApi.exportScheduleRecord(queryParams)
    download.excel(data, '配送管理-调度生产记录.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const handleSyncQuarter = async () => {
  try {
    await message.exportConfirm('同步季度计划会重置今日计划和生产计划，是否同步？')
    exportLoading.value = true
    await ScheduleRecordApi.syncQuarterPlan()
    message.success('同步成功')
    await getList()
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 列配置逻辑（保留原始，仅修改数量列） */
interface TableColumn {
  prop: string
  label: string
  width?: number
  editable?: boolean
  editWidth?: number
  type?: string
}

const allColumns: TableColumn[] = [
  {
    prop: 'inboundFlight',
    label: '进港航班',
    width: 150,
    editable: true,
    editWidth: 120,
    type: '文本'
  },
  { prop: 'flightNo', label: '航班号', width: 120, type: '文本' },
  { prop: 'route', label: '航线', width: 180, type: '文本' }, // 新增航线列
  { prop: 'machineNo', label: '机号', width: 140, editable: true, editWidth: 110, type: '文本' },
  { prop: 'depTime', label: '起飞时间', width: 100, editable: true, editWidth: 100, type: '时间' },
  {
    prop: 'preLandingTime',
    label: '预落时间',
    width: 100,
    editable: true,
    editWidth: 100,
    type: '时间'
  },
  {
    prop: 'inboundTime',
    label: '实落时间',
    width: 100,
    editable: true,
    editWidth: 100,
    type: '时间'
  },
  { prop: 'recordDate', label: '日期', width: 120, type: '日期' },
  {
    prop: 'airportStands',
    label: '机位',
    width: 130,
    editable: true,
    editWidth: 100,
    type: '文本'
  },
  { prop: 'remarks', label: '备注', width: 200, editable: true, editWidth: 200, type: '文本' },
  // 整合数量相关列
  {
    prop: 'quantity',
    label: '数量',
    width: 300,
    type: '复合'
  },
  {
    prop: 'specialRemarks',
    label: '特殊说明',
    width: 200,
    editable: true,
    editWidth: 200,
    type: '文本'
  },
  { prop: 'aircraftType', label: '机型', width: 120, type: '文本' },
  { prop: 'airlineComp', label: '所属公司', width: 120, type: '状态' },
  { prop: 'airlinePattern', label: '航班类型', width: 120, type: '状态' },
  { prop: 'company', label: '所属公司', width: 120, type: '文本' },
  { prop: 'createTime', label: '创建时间', width: 180, type: '时间' },
  { prop: 'pstatus', label: '生产状态', width: 120, type: '状态' }
]

const tableRowClassName = ({ rowData }: { rowData: any }) => {
  if (selectedRow.value && selectedRow.value.id == rowData.id) {
    return 'row-selected'
  }
  return rowData?.markStatus === 1 ? 'row-first' : ''
}

/** 打开数量编辑弹窗 */
const openQuantityEdit = (row: ScheduleRecordVO) => {
  // 深拷贝行数据到当前编辑对象
  currentRow.value = JSON.parse(JSON.stringify(row))
  quantityDialogVisible.value = true
}

/** 自动刷新（保留原始） */
const refreshInterval = ref(120000)
const autoRefreshTimer = ref<NodeJS.Timeout | null>(null)
const autoRefreshEnabled = ref(true)

const startAutoRefresh = () => {
  if (autoRefreshTimer.value) clearInterval(autoRefreshTimer.value)
  autoRefreshTimer.value = setInterval(() => getList(), refreshInterval.value)
}

const stopAutoRefresh = () => {
  if (autoRefreshTimer.value) clearInterval(autoRefreshTimer.value)
}

/** 初始化（保留原始） */
onMounted(async () => {
  try {
    await nextTick()
    await getList()
    if (autoRefreshEnabled.value) startAutoRefresh()
  } catch (err) {
    message.error('页面初始化失败')
  }
})

onUnmounted(() => stopAutoRefresh())

// 核心：操作列表头仅显示“操作”文本（无交互）
const tableV2Columns = computed<Column<ScheduleRecordVO>[]>(() => {
  // 动态列逻辑（保持不变）
  const baseColumns = allColumns.map((column) => ({
    key: column.prop,
    title: column.label,
    dataKey: column.prop,
    width: column.width || 120,
    cellRenderer: ({ cellData, rowData }) => {
      const row = rowData as ScheduleRecordVO
      const cellValue = cellData?.toString() || ''
      const isDisabled = row.pstatus === 12

      // 处理新的数量复合列 - 仅显示数据，点击打开弹窗
      if (column.prop === 'quantity') {
        return (
          <div
            style="display: flex; flex-direction: column; gap: 2px; width: 100%; cursor: pointer;"
            onClick={() => openQuantityEdit(row)}
          >
            {/* 第一行：标题行 */}
            <div style="display: flex; font-weight: 500; font-size: 12px;">
              <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                <ElTooltip content="J" placement="top">
                  <span>J</span>
                </ElTooltip>
              </div>
              /
              <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                <ElTooltip content="S" placement="top">
                  <span>S</span>
                </ElTooltip>
              </div>
              /
              <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                <ElTooltip content="G" placement="top">
                  <span>G</span>
                </ElTooltip>
              </div>
              /
              <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                <ElTooltip content="Y" placement="top">
                  <span>Y</span>
                </ElTooltip>
              </div>
            </div>

            {/* 第二行：销售数量行 */}
            <div style="display: flex; font-size: 12px;">
              <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                <ElTooltip content={row.crewSaleQty || '-'} placement="top">
                  <span>{row.crewSaleQty || '-'}</span>
                </ElTooltip>
              </div>
              /
              <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                <ElTooltip content={row.bussClassSaleQty || '-'} placement="top">
                  <span>{row.bussClassSaleQty || '-'}</span>
                </ElTooltip>
              </div>
              /
              <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                <ElTooltip content={row.premEcoClassSaleQty || '-'} placement="top">
                  <span>{row.premEcoClassSaleQty || '-'}</span>
                </ElTooltip>
              </div>
              /
              <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                <ElTooltip content={row.ecoClassSaleQty || '-'} placement="top">
                  <span>{row.ecoClassSaleQty || '-'}</span>
                </ElTooltip>
              </div>
            </div>
            {/* 第三行：数量行 */}
            <div style="display: flex; font-size: 12px;">
              <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                <ElTooltip content={row.crewQty || '-'} placement="top">
                  <span>{row.crewQty || '-'}</span>
                </ElTooltip>
              </div>
              /
              <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                <ElTooltip content={row.bussClassQty || '-'} placement="top">
                  <span>{row.bussClassQty || '-'}</span>
                </ElTooltip>
              </div>
              /
              <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                <ElTooltip content={row.premEcoClassQty || '-'} placement="top">
                  <span>{row.premEcoClassQty || '-'}</span>
                </ElTooltip>
              </div>
              /
              <div style="width: 25%; text-align: center; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                <ElTooltip content={row.ecoClassQty || '-'} placement="top">
                  <span>{row.ecoClassQty || '-'}</span>
                </ElTooltip>
              </div>
            </div>
          </div>
        )
      }

      if (column.editable) {
        if (isTimeColumn(column.prop)) {
          return (
            <ElInput
              modelValue={cellValue}
              onUpdate:modelValue={(val) => {
                row[column.prop] = val
              }}
              placeholder={`请输入${column.label}(HHmm)`}
              clearable
              class={`!w-${column.editWidth || 100}px`}
              onInput={(e) => handleColumnTimeInput(row, column.prop, e.target.value)}
              onBlur={() => handleColumnTimeBlur(row, column.prop)}
              showWordLimit
              disabled={isDisabled}
            />
          )
        }

        if (isNumberColumn(column.prop)) {
          return (
            <ElInput
              modelValue={cellValue}
              onUpdate:modelValue={(val) => {
                row[column.prop] = val
              }}
              placeholder={`请输入${column.label}`}
              clearable
              class={`!w-${column.editWidth || 100}px`}
              onInput={(e) => handleNumberInput(row, column.prop, e.target.value)}
              onBlur={() => handleNumberBlur(row, column.prop)}
              showWordLimit
              disabled={isDisabled}
            />
          )
        }

        return (
          <ElInput
            modelValue={cellValue}
            onUpdate:modelValue={(val) => {
              row[column.prop] = val
            }}
            placeholder={`请输入${column.label}`}
            clearable
            class={`!w-${column.editWidth || 100}px`}
            onBlur={() => handleTextBlur(row, column.prop)}
            showWordLimit
            disabled={isDisabled}
          />
        )
      }

      if (column.prop === 'pstatus') {
        return <ElTag type="primary">{getStatusLabel(cellData)}</ElTag>
      }

      // 特殊列：航空公司
      if (column.prop === 'airlineComp') {
        return h(DictTag, {
          type: DICT_TYPE.PPLAN_AIRLINE_ID,
          value: row.airlineComp
        })
      }
      // 特殊列：航线类型
      if (column.prop === 'airlinePattern') {
        return h(DictTag, {
          type: DICT_TYPE.PPLAN_AIRLINE_TYPE,
          value: row.airlinePattern
        })
      }
      // 新增：航线列渲染（depLoc - arrLoc拼接）
      if (column.prop === 'route') {
        const depLoc = row.depLoc || ''
        const arrLoc = row.arrLoc || ''
        const routeText = depLoc && arrLoc ? `${depLoc} - ${arrLoc}` : '-'
        return (
          <ElTooltip content={routeText} placement="top">
            <div class="overflow-hidden whitespace-nowrap text-ellipsis w-full flex items-center ">
              {routeText}
            </div>
          </ElTooltip>
        )
      }

      if (column.prop === 'createTime') {
        return (
          <ElTooltip content={formatDate(cellData) || '-'}>
            <span class="flex items-center">
              <ElIcon class="mr-2">
                <Timer />
              </ElIcon>
              {formatDate(cellData) || '-'}
            </span>
          </ElTooltip>
        )
      }

      if (isTimeColumn(column.prop)) {
        return (
          <ElTooltip content={formatDisplayTime(cellValue) || '-'}>
            <span>{formatDisplayTime(cellValue) || '-'}</span>
          </ElTooltip>
        )
      }

      return <span>{cellValue || '-'}</span>
    }
  }))

  // 操作列：表头仅显示“操作”文本（无交互）
  const actionColumn: Column<ScheduleRecordVO> = {
    key: 'operations',
    title: '操作', // 仅文本，无点击事件
    width: 180,
    fixed: 'right',
    cellRenderer: ({ rowData }) => {
      const row = rowData as ScheduleRecordVO
      return (
        <div style="display: flex; align-items: center; justify-content: center; gap: 8px;">
          <ElButton
            type="primary"
            link
            size="small"
            onClick={() => openForm('update', row.flightNo)}
          >
            查看详情
          </ElButton>

          <ElButton
            type="primary"
            link
            size="small"
            onClick={() => openAddForm(row.flightNo, row.recordDate)}
          >
            加餐
          </ElButton>

          <ElDropdown
            v-slots={{
              dropdown: () => (
                <ElDropdownMenu>
                  {ProcessStatus.map((item) => (
                    <ElDropdownItem
                      key={item.value}
                      onClick={() => handleStatusChange(row, item.value)}
                    >
                      {item.label}
                    </ElDropdownItem>
                  ))}
                </ElDropdownMenu>
              )
            }}
          >
            <ElButton type="primary" link size="small">
              <ElIcon class="mr-1">
                <DArrowRight />
              </ElIcon>
              更多
            </ElButton>
          </ElDropdown>
        </div>
      )
    }
  }

  return [...baseColumns, actionColumn]
})
</script>

<style scoped>
/* 保留原始所有样式 */
:deep(.el-table-v2__row.row-selected) {
  background-color: var(--el-table-current-row-bg-color);
}

:deep(.el-table__row.row-first),
:deep(.el-table-v2__row.row-first) {
  background-color: #f26a6e !important;
}
</style>
